package com.maxd.service.lucky;

import com.maxd.model.*;
import com.maxd.respository.helpTask.HelpLuckyValueRepository;
import com.maxd.respository.lucky.LuckyQueueRecordJpaRepository;
import com.maxd.respository.lucky.LuckyQueueRecordRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.helpTask.IHelpLuckyValueService;
import com.maxd.service.message.IMessageService;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.userinfo.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 幸运值队列
 */
@Service
public class LuckyQueueRecordServiceImpl implements ILuckyQueueRecordService {

    @Autowired
    private  LuckyQueueRecordJpaRepository luckyQueueRecordJpaRepository;
    @Autowired
    private  LuckyQueueRecordRepository luckyQueueRecordRepository;
    @Autowired
    private  ILuckyValueQueueService iLuckyValueQueueService;
    @Autowired
    private  UserJpaRepository userJpaRepository;
    @Autowired
    private  UserRepository userRepository;
    @Autowired
    private  ILuckyQueueService iLuckyQueueService;
    @Autowired
    private  IMoneyDetailsService iMoneyDetailsService;
    @Autowired
    private  ILuckyQueueRecordService iLuckyQueueRecordService;
    @Autowired
    private  ILuckyValueQueueService luckyValueQueueService;
    @Autowired
    private  IHelpLuckyValueService luckyValueService;
    @Autowired
    private  ILuckyQueueService luckyQueueService;
    @Autowired
    private HelpLuckyValueRepository helpLuckyValueRepository;
    @Autowired
    private IUserService userService;
    @Autowired
    private IMessageService iMessageService;




    @Override
    public LuckyQueueRecord saveBody(LuckyQueueRecord luckyQueueRecord) {
        return luckyQueueRecordJpaRepository.save(luckyQueueRecord);
    }

    @Override
    @Transactional
    public int auditLuckyQueueRecord(String ids, Integer state, String auditContent) {
        for(String i:ids.split(",")){
            Long id=Long.parseLong(i);
            LuckyQueueRecord luckyQueueRecord = luckyQueueRecordRepository.selectById(id);
            if(luckyQueueRecord!=null && luckyQueueRecord.getState()==0){
                LuckyQueue oldLuckyQueue=null;
                LuckyValueQueue oldLuckyValueQueue = iLuckyValueQueueService.selectLuckyValueQueueByUserId(luckyQueueRecord.getUserId());
                if(state==1){
                    luckyQueueRecordRepository.updateLuckyQueueRecord(id,state,"同意");
                    if(oldLuckyValueQueue!=null){
                        oldLuckyQueue = iLuckyQueueService.selectLuckyQueueById(oldLuckyValueQueue.getLuckyQueueId());
                    }
                    LuckyQueue newLuckyQueue = iLuckyQueueService.selectLuckyQueueById(luckyQueueRecord.getLuckyQueueId());
                    closeAnAccount(luckyQueueRecord.getUserId(),oldLuckyQueue,newLuckyQueue,luckyQueueRecord);
                }else{
                    luckyQueueRecordRepository.updateLuckyQueueRecord(id,state,auditContent);
                    if(oldLuckyValueQueue!=null){
                        iLuckyValueQueueService.updateLuckyValueQueue(1,luckyQueueRecord.getUserId());
                    }
                    LuckyValueQueue luckyValueQueue = iLuckyValueQueueService.selectLuckyValueQueueByUserId(luckyQueueRecord.getUserId());
                    //获取当前人的队列  拒绝后重新判断
                    List<Long> longs = iLuckyValueQueueService.selectLuckyQueueUserIdByLuckyQueueId(luckyValueQueue.getLuckyQueueId());
                    for(Long userId1:longs){
                        UserInfo userInfo1 = userJpaRepository.findById(userId1).orElse(null);
                        if(userInfo1!=null){
                            updateLucky(userInfo1);
                        }
                    }
                }
            }
        }
        return 0;
    }


    /**
     * 审核通过后进行结算
     */
    private void closeAnAccount(Long userId,LuckyQueue oldLuckyQueue,LuckyQueue newLuckyQueue,LuckyQueueRecord luckyQueueRecord){
        //晋级成功之后先看是否有邀请人 如果有邀请人则给邀请人对应的邀请赏金
        UserInfo userInfo = userJpaRepository.findById(userId).orElse(null);
        if(userInfo!=null){
            if(StringUtils.isNotBlank(userInfo.getInvitation())){
                UserInfo userByRelationId = userRepository.getUserByRelationId(userInfo.getInvitation());
                if(userByRelationId!=null){
                    //给推荐人奖励晋级等级推荐金额
                    userRepository.updateJiFenAdd(newLuckyQueue.getRecommendMoney().toString(),userByRelationId.getId());
                    iMoneyDetailsService.saveBody(userByRelationId.getId(),1,3,"红包榜收入","红包榜推荐奖励，晋级成员："+userInfo.getNickName()+",推荐奖金额:"+newLuckyQueue.getRecommendMoney().toString(),newLuckyQueue.getRecommendMoney());
                }
            }
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //先判断自己有没有上一个等级
            if(oldLuckyQueue!=null){
                //晋级成功之后给自己增加金额 给自己奖励上一个等级的晋级红包（派送红包）
                helpLuckyValueRepository.updateHelpLuckyValueAccruingAmounts(userInfo.getId(),oldLuckyQueue.getHandOut());
                userRepository.updateJiFenAdd(oldLuckyQueue.getHandOut().toString(),userInfo.getId());
                iMoneyDetailsService.saveBody(userInfo.getId(),1,3,"红包榜收入","红包榜晋级奖励金额:"+oldLuckyQueue.getHandOut().toString(),oldLuckyQueue.getHandOut());
                iLuckyValueQueueService.updateLuckyValueQueue(luckyQueueRecord.getUserId(),luckyQueueRecord.getLuckyQueueId(),1,sdf.format(new Date()));
            }else{
                //没有上级则默认创建一个
                LuckyValueQueue luckyValueQueue=new LuckyValueQueue();
                luckyValueQueue.setUserId(userId);
                luckyValueQueue.setCreateTime(sdf.format(new Date()));
                luckyValueQueue.setLuckyQueueId(newLuckyQueue.getId());
                luckyValueQueue.setState(1);
                iLuckyValueQueueService.saveBody(luckyValueQueue);
            }
            //获取当前人晋级的队列的所有人 进行判断。。。
            List<Long> longs = iLuckyValueQueueService.selectLuckyQueueUserIdByLuckyQueueId(luckyQueueRecord.getLuckyQueueId());
            for(Long userId1:longs){
                UserInfo userInfo1 = userJpaRepository.findById(userId1).orElse(null);
                if(userInfo1!=null){
                    updateLucky(userInfo1);
                }
            }
        }
    }

    /**
     * 计算幸运值队列是否晋级  判断条件必须同时满足
     * 1 积分达到
     * 2 邀请的人必须成为同等或以上会员
     * 3 队列在1-13之间 必须满足13个人 之后9的倍数 必须满足
     */
    private int updateLucky(UserInfo userByWxId){
        MessageInfo messageInfo = new MessageInfo();
        //先判断是否已经发起过申请
        LuckyQueueRecord oldLuckyQueueRecord = iLuckyQueueRecordService.selectByUserId(userByWxId.getId());
        if(oldLuckyQueueRecord==null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            LuckyValueQueue luckyValueQueue = luckyValueQueueService.selectLuckyValueQueueByUserId(userByWxId.getId());
            HelpLuckyValue helpLuckyValue = luckyValueService.selectByUserId(userByWxId.getId());
            //获取平台积分晋级积分条件 判断当前积分是否满足 积分晋级条件
            List<LuckyQueue> luckyQueues = luckyQueueService.selectLuckyQueueListAsc();
            //判断是否已经达到最高等级
            if((luckyValueQueue==null)||(!luckyValueQueue.getLuckyQueueId().equals(luckyQueues.get(luckyQueues.size()-1).getId()))) {
                for(int j=0;j<luckyQueues.size();j++){
                    if (helpLuckyValue.getLuckyValue() >= luckyQueues.get(j).getLuckyValue()) {
                        //如果用户所在队列为空  则必须是第一队列
                        if (luckyValueQueue == null) {
                            //第一队列条件满足  提交晋级申请
                            LuckyQueueRecord luckyQueueRecord = new LuckyQueueRecord();
                            luckyQueueRecord.setLuckyQueueId(luckyQueues.get(0).getId());
                            luckyQueueRecord.setUserId(userByWxId.getId());
                            luckyQueueRecord.setCreateTime(sdf.format(new Date()));
                            luckyQueueRecord.setState(0);
                            iLuckyQueueRecordService.saveBody(luckyQueueRecord);
                            messageInfo.setContent(userByWxId.getNickName() + " 您好！您的红包榜晋级条件已满足！自动帮您申请晋级新的队列:"+luckyQueues.get(0).getName());
                            if (userByWxId.getClientid() != null) {
                                userService.pushToSingle("队列晋级通知", userByWxId.getNickName() + " 您好！您的红包榜晋级条件已满足！自动帮您申请晋级新的队列:"+luckyQueues.get(0).getName(), userByWxId.getClientid());
                            }
                            messageInfo.setState(String.valueOf(6));
                            messageInfo.setTitle("队列晋级通知！");
                            messageInfo.setUserName(userByWxId.getNickName());
                            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
                            iMessageService.saveBody(messageInfo);
                            return 1;
                        } else {
                            //除晋级第一队列外 其他队列晋级需要满足条件方可
                            if(luckyQueues.get(j).getSort()!=1){
                            LuckyQueue luckyQueue1 = luckyQueueService.selectLuckyQueueById(luckyValueQueue.getLuckyQueueId());
                                //用户所在队列必须等于前一个队列 才可晋级
                                if (luckyQueue1.getSort() .equals( luckyQueues.get(j-1).getSort())) {
                                    //判断邀请的好友是否满足条件  邀请的好友是否达到当前级别或者级别以上
                                    Integer integer = luckyValueQueueService.selectUserLuckyQueueByInvitation(userByWxId.getRelationId(), luckyQueues.get(j-1).getSort());
                                    //邀请的好友必须大于等于自己当前等级晋级所需人数
                                    if (integer != null && integer >= luckyQueue1.getNumberOfPeople()) {
                                        //判断自己所在当前队列的位置
                                        Integer integer1 = luckyValueQueueService.selectLuckQueueLocationByUserId(userByWxId.getId(), luckyValueQueue.getLuckyQueueId());
                                        //当前队列总人数
                                        Integer integer2 = luckyValueQueueService.selectLuckQueueCount(luckyValueQueue.getLuckyQueueId());
                                        //队列晋级条件 前13名必须凑够13人方可晋级  后面按照9人一队为顺序 方可晋级
                                        if (integer1 != null && integer2 != null) {
                                            if (integer1 <= luckyQueue1.getStartPerson()) {
                                                //队列人数大于13人 提交晋级申请
                                                if (integer2 >= luckyQueue1.getStartPerson()) {
                                                    //条件满足 提交晋级申请
                                                    LuckyQueueRecord luckyQueueRecord = new LuckyQueueRecord();
                                                    luckyQueueRecord.setLuckyQueueId(luckyQueues.get(j).getId());
                                                    luckyQueueRecord.setUserId(userByWxId.getId());
                                                    luckyQueueRecord.setCreateTime(sdf.format(new Date()));
                                                    luckyQueueRecord.setState(0);
                                                    iLuckyQueueRecordService.saveBody(luckyQueueRecord);
                                                    luckyValueQueueService.updateLuckyValueQueue(2,luckyValueQueue.getUserId());
                                                    messageInfo.setContent(userByWxId.getNickName() + " 您好！您的红包榜晋级条件已满足！自动帮您申请晋级新的队列:"+luckyQueues.get(j).getName());
                                                    if (userByWxId.getClientid() != null) {
                                                        userService.pushToSingle("队列晋级通知", userByWxId.getNickName() + " 您好！您的红包榜晋级条件已满足！自动帮您申请晋级新的队列:"+luckyQueues.get(j).getName(), userByWxId.getClientid());
                                                    }
                                                    messageInfo.setState(String.valueOf(6));
                                                    messageInfo.setTitle("队列晋级通知！");
                                                    messageInfo.setUserName(userByWxId.getNickName());
                                                    messageInfo.setUserId(String.valueOf(userByWxId.getId()));
                                                    iMessageService.saveBody(messageInfo);
                                                    return 1;
                                                }
                                            } else {
                                                //根据当前所在位置 进行计算 必须满足9人方可晋级
                                                integer1 = integer1 - luckyQueue1.getStartPerson();
                                                integer2 = integer2 - luckyQueue1.getStartPerson();
                                                //根据当前位置和9的倍数 获取所在队列
                                                int i = integer1 / luckyQueue1.getIntervalPerson();
                                                //判断是否能够除尽
                                                int count;
                                                if (integer1 % luckyQueue1.getIntervalPerson() == 0) {
                                                    count = i * luckyQueue1.getIntervalPerson();
                                                } else {
                                                    count = (i * luckyQueue1.getIntervalPerson()) + luckyQueue1.getIntervalPerson();
                                                }
                                                //判断自己所在队列人数是否满足条件
                                                if (integer2 >= count) {
                                                    //条件满足 提交晋级申请
                                                    LuckyQueueRecord luckyQueueRecord = new LuckyQueueRecord();
                                                    luckyQueueRecord.setLuckyQueueId(luckyQueues.get(j).getId());
                                                    luckyQueueRecord.setUserId(userByWxId.getId());
                                                    luckyQueueRecord.setCreateTime(sdf.format(new Date()));
                                                    luckyQueueRecord.setState(0);
                                                    iLuckyQueueRecordService.saveBody(luckyQueueRecord);
                                                    luckyValueQueueService.updateLuckyValueQueue(2,luckyValueQueue.getUserId());
                                                    messageInfo.setContent(userByWxId.getNickName() + " 您好！您的红包榜晋级条件已满足！自动帮您申请晋级新的队列:"+luckyQueues.get(j).getName());
                                                    if (userByWxId.getClientid() != null) {
                                                        userService.pushToSingle("队列晋级通知", userByWxId.getNickName() + " 您好！您的红包榜晋级条件已满足！自动帮您申请晋级新的队列:"+luckyQueues.get(j).getName(), userByWxId.getClientid());
                                                    }
                                                    messageInfo.setState(String.valueOf(6));
                                                    messageInfo.setTitle("队列晋级通知！");
                                                    messageInfo.setUserName(userByWxId.getNickName());
                                                    messageInfo.setUserId(String.valueOf(userByWxId.getId()));
                                                    iMessageService.saveBody(messageInfo);
                                                    return 1;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return 0;
    }



    @Override
    public LuckyQueueRecord selectByUserId(Long userId){
        return luckyQueueRecordRepository.selectByUserId(userId);
    }


    @Override
    public Page<Map<String,Object>> selectLuckyQueueRecordList(Pageable pageable) {
        return luckyQueueRecordRepository.selectLuckyQueueRecordList(pageable);
    }

    @Override
    public Page<Map<String, Object>> selectLuckyQueueRecordByUserId(Pageable pageable, Long userId) {
        return luckyQueueRecordRepository.selectLuckyQueueRecordByUserId(pageable,userId);
    }
}
